<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model layout="inline" ref="ruleForm" :model="queryParam">
          <z-form-item
            :datas="fieldArr"
            :form="queryParam"
            :submitAction="{ show: true, toggle: false }"
            @change="getChange"
            @onSubmit="onQuery"
            @onReset="onResetForm"
          />
        </a-form-model>
      </div>
    </a-card>
    <a-card :bordered="false">
      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <div>
          <a-button type="primary" @click="clickPush()">新建</a-button>
          <a-button :disabled="isDisabled" @click="handleOperate('enable')">启用</a-button>
          <a-button :disabled="isDisabled" @click="handleOperate('disable')">停用</a-button>
          <a-button :disabled="isDisabled" @click="handleOperate('delete')">删除</a-button>
        </div>
      </div>
      <!-- 表格展示 -->
      <div class="table-page-content">
        <z-table
          ref="table"
          rowKey="id"
          :showAlert="true"
          :showSelection="true"
          :loading="loading"
          :columns="columns"
          :dataSource="pageData"
          @selectedRow="onSelectedRow"
          @change="onTableChange"
        />
      </div>
    </a-card>
    <j-modal
      :title="title"
      :width="1100"
      :visible="visible"
      switchFullscreen
      :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭"
    >
      <div class="table-page-search-wrapper">
        <a-form-model layout="inline" ref="subForm" :model="model" :rules="validatorRules">
          <z-form-item :datas="fieldArrModal" :form="model" :rules="validatorRules" :gutter="4" @rows="getChange">
            <!--//自定义清除框选区域-->
            <template slot="slots-clearArea" v-if="!disableSubmit">
              <a-button type="danger" ghost @click="clearLayer">清除框选区域</a-button>
            </template>
          </z-form-item>
        </a-form-model>
      </div>
      <map-draw ref="mapDraw" drawBool v-model="chartVOList" style="min-height: 600px" />
    </j-modal>
  </div>
</template>

<script>
import * as alarmServiceApi from '@/api/sjsk/alarmService'
import mapDraw from '../modules/mapDraw'
export default {
  components: { mapDraw },
  data() {
    return {
      loading: false,
      disableSubmit: false,
      isDisabled: true,
      queryParam: {},
      title: '新建',
      model: {},
      chartVOList: [],
      visible: false,
      confirmLoading: false,
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
      },
      fieldArr: [
        { label: '区域名称', prop: 'name', tagType: 'input', span: 6 },
        { label: '区域类型', prop: 'type', tagType: 'dict-select', dictCode: 'area_type', span: 6 },
        {
          label: '状态',
          prop: 'state',
          tagType: 'dict-select',
          dictOptions: [
            { text: '请选择', value: '' },
            { text: '使用中', value: '1' },
            { text: '停用', value: '2' },
          ],
          span: 6,
        },
        { label: '创建时间', prop: 'createTime', tagType: 'range-picker', format: 'YYYY-MM-DD', span: 6 },
      ],
      columns: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 80,
          align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize + (index + 1)}`, //序号分页后连续
        },
        {
          title: '区域名称',
          dataIndex: 'name',
          width: 240,
          align: 'left',
          customRender: (text) => {
            return <j-ellipsis value={text} length={20} />
          },
        },
        {
          title: '区域类型',
          dataIndex: 'areaType',
          width: 120,
          align: 'center',
          customRender: (text) => {
            return this.$filterDictTextByCache('area_type', text)
          },
        },
        {
          title: '状态',
          dataIndex: 'state',
          width: 80,
          align: 'center',
          customRender: (text) => {
            return (
              <span class={text == 1 ? 'text_color_1' : text == 2 ? 'text_color_2' : ''}>
                {text == 1 ? '使用中' : text == 2 ? '停用' : ''}
              </span>
            )
          },
        },
        { title: '创建时间', dataIndex: 'createTime', width: 140, align: 'center' },
        {
          title: '操作',
          width: 140,
          align: 'center',
          dataIndex: 'action',
          customRender: (text, record, index) => {
            return (
              <a-space size={6}>
                <a-button type="link" style={'padding:0'} onClick={(event) => this.clickPush('details', record)}> 查看 </a-button>
                <a-button type="link" style={'padding:0'} onClick={(event) => this.clickPush('edit', record)}> 编辑 </a-button>
                <a-button
                  type="link"
                  style={'padding:0'}
                  onClick={(event) => this.handleOperate(record.state == 1 ? 'disable' : 'enable', record)}
                >
                  {record.state == 1 ? '停用' : '启用'}
                </a-button>
                <a-button type="link" style={'padding:0'} onClick={(event) => this.handleOperate('delete', record)}> 删除 </a-button>
              </a-space>
            )
          },
        },
      ],
      fieldArrModal: [
        { label: '区域名称', prop: 'name', tagType: 'input', span: 10, disabled: false },
        { label: '区域类型', prop: 'type', tagType: 'dict-select', dictCode: 'area_type', span: 10, disabled: false },
        { label: '', prop: 'clearArea', span: 4 },
        { label: '行政区划', prop: 'adminDivisions', tagType: 'linkage-area', span: 23, toggle: false, disabled: false },
      ],
      validatorRules: {
        name: [{ required: true, message: '请输入关键词!' }],
        type: [{ required: true, message: '请选择关键词级别!' }],
        adminDivisions: [{ required: true, message: '请选择关键词类别!' }],
      },
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: {},
    }
  },
  watch: {
    'model.type': {
      immediate: true,
      deep: true,
      handler(val) {
        this.fieldArrModal.forEach((item) => {
          if (item.hasOwnProperty('toggle')) {
            item.toggle = val == 1 ? true : false //区域类型为执行地时，显示行政区划选项
          }
        })
      },
    },
    'disableSubmit': {
      immediate: true,
      deep: true,
      handler(val) {
        this.fieldArrModal.forEach((item) => {
          if (item.hasOwnProperty('disabled')) {
            item.disabled = val
          }
        })
      }
    }
  },
  async mounted() {
    this.onQuery()
  },
  methods: {
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.queryParam = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onTableChange(pagination, pageFilter, sorter) {
      this.pageFilter = Object.assign({}, this.pageFilter, pagination)
      this.refreshTable()
    },
    refreshTable() {
      let { createTime, ...dataParam } = this.queryParam // 剔除createTime元素，dataParam最新的对象
      let queryParam = Object.assign({}, dataParam, this.pageFilter)
      this.loading = true
      alarmServiceApi
        .getRegionList(queryParam)
        .then((res) => {
          this.loading = false
          if (res.success) {
            this.pageData = res.result ? res.result : {}
            this.$refs.table.onClearRowKeys()
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    onSelectedRow(keys) {
      this.isDisabled = keys.length > 0 ? false : true
    },
    // 业务操作-启用、停用
    handleOperate(type, record) {
      let selectList = this.$refs.table.getSelectedRows()
      let ids = selectList.map((item) => item.id)
      let that = this
      let title,
        form = {}
      if (type == 'enable') {
        ;(title = '启用'), (form = { ids: record ? [record.id] : ids, start: 1 })
      } else if (type == 'disable') {
        ;(title = '停用'), (form = { ids: record ? [record.id] : ids, start: 2 })
      } else if (type == 'delete') {
        ;(title = '删除'), (form = { ids: record ? [record.id] : ids, start: 9 })
      }
      this.$confirm({
        title: `确定${title}${record ? '该' : '下列'}区域？`,
        onOk() {
          let api = type === 'delete' ? alarmServiceApi.deleteRegion(form) : alarmServiceApi.enableRegion(form)
          if (!api) return
          api
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message ? res.message : `${title}操作成功！`)
                that.onQuery()
              } else {
                that.$message.warn(res.message ? res.message : `${title}操作失败！`)
              }
            })
            .catch((e) => {
              that.$message.warn('操作失败！')
            })
        },
      })
    },
    // 获取组件的时间， prop为对应的字段，date为选中的时间值
    getChange(prop, value) {
      console.log(prop, value)
      if (prop === 'createTime') {
        this.$set(this.queryParam, 'beginTime', value[0])
        this.$set(this.queryParam, 'endTime', value[1])
      }
      if (prop === 'adminDivisions') {
        let lastData = value.length > 0 ? value[value.length - 1] : {}
        let dataString = value.map((v) => v.key)
        this.$set(this.model, 'adminDivision', Object.keys(lastData).length > 0 && lastData.key ? lastData.key : '')
        this.$set(this.model, 'adminDivisionStr', dataString.toString())
      }
    },
    // 新建
    clickPush(type, record) {
      this.visible = true
      this.chartVOList = []
      if (record) {
        alarmServiceApi.getDetailsById(record.id).then((res) => {
          if (res.success) {
            const { result } = res
            this.model = Object.assign({}, result)
            this.$set(this.model, 'adminDivisions', result.adminDivisionStr ? result.adminDivisionStr.split(',') : [])
            this.$set(this.model, 'id', record.id)
            result.chartVOList.forEach(i => {
              this.chartVOList.push([Number(i.latitude), Number(i.longitude)])
            })
            console.log(this.chartVOList)
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch((e) => {
          this.$message.warn('请求失败！')
        })
      }
      this.disableSubmit = type === 'details'? true:false
      this.title =
        type === 'details' && record && Object.keys(record).length > 0 && record.id
          ? '查看区域'
          : type === 'edit' && record && Object.keys(record).length > 0 && record.id
          ? '编辑区域'
          : '新增区域'
    },
    handleOk() {
      const parameter = Object.assign({}, this.model)
      this.$refs.subForm.validate((valid) => {
        if (valid) {
          console.log(this.chartVOList)
          let chartVOList = []
          if(this.chartVOList && this.chartVOList.length==0) {
            this.$message.warn('未绘制框选区域')
            return
          }
          if (this.chartVOList.length===3) {
            chartVOList = [{ latitude: this.chartVOList[0], longitude: this.chartVOList[1], radius: this.chartVOList[2] }]
          } else {
            this.chartVOList.forEach(i => {
              chartVOList.push({ latitude: i[0], longitude: i[1] })
            })
          }
          this.$set(parameter, 'chartVOList', chartVOList)
          let api = null
          if (Object.keys(parameter).length > 0 && parameter.id) {
            api = alarmServiceApi.updateRegion(parameter)
          } else {
            api = alarmServiceApi.createRegion(parameter)
          }
          if (!api) return
          api
            .then((res) => {
              this.confirmLoading = false
              if (res.success) {
                this.$message.success(res.message ? res.message : '操作成功')
                this.onQuery()
                this.handleCancel()
              } else {
                this.$message.warn(res.message ? res.message : '操作失败')
              }
            })
            .catch((e) => {
              this.$message.warn('操作失败！')
              this.confirmLoading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCancel() {
      this.visible = false
      this.model = {}
    },
    clearLayer() {
      this.$nextTick(()=> {
        this.$refs.mapDraw.clearLayer()
      })
    },
    // 隔数组
    group(array, subGroupLength) {
      let index = 0;
      let newArray = [];
      while (index < array.length) {
        newArray.push(array.slice(index, (index += subGroupLength)));
      }
      return newArray;
    },
  },
}
</script>

<style scoped lang="less">
.text_color_1 {
  color: #70b603;
}
.text_color_2 {
  color: #d9001b;
}
</style>
